package com.demo.dto;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.commons.codec.digest.DigestUtils;

import com.demo.kit.StrKit;
import com.demo.model.User;

public class AccessToken {
	private String id;
	private String loginTime;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getLastLoginTime() {
		return loginTime;
	}
	public void setLastLoginTime(String loginTime) {
		this.loginTime = loginTime;
	}
	public AccessToken(String id, String loginTime) {
		super();
		this.id = id;
		this.loginTime = loginTime;
	}
	@Override
	public String toString() {
		return "AccessToken [id=" + id + ", lastLoginTime=" + loginTime
				+ "]";
	}
	
	public String signature(String salt){
//		String salt = PropKit.get("salt");
		String[] stringArray = {this.id, this.loginTime, salt};
		String sign = StrKit.join(stringArray, ",");
		sign = DigestUtils.md5Hex(sign);
		return sign;
	}
	public String getAccessToken(String sign){
		String[] stringArray = {this.id, this.loginTime, sign};
		String accessToken = StrKit.join(stringArray, ",");
		return accessToken;
	}
	public static boolean validateToken(String token){
		if ("".equals(token)) {
			return false;
		}
		String[] strings = token.split(",");
		String id = strings[0];
		String loginTime = strings[1];
		String sign = strings[2];
		User user = User.dao.findById(Integer.parseInt(id));
		AccessToken accessToken = new AccessToken(id, loginTime);
		String salt = user == null ? "" : user.getStr("salt");
		String currentSign = accessToken.signature(salt);
		if (currentSign.equals(sign)) {
			return true;
		}
		return false;
	}
	
	public static int getUserId(String token){
		if (token == null || "".equals(token)) {
			return 0;
		}
		String[] strings = {};
		try {
			token = URLDecoder.decode(token, "utf-8");
			strings = token.split(",");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return 0;
		}
		return Integer.parseInt(strings[0]);
	}
}
